A dictionary is a list of associations composed by a unique key and corresponding structures. Dictionaries are mutable, like lists.
The key must be an immutable type, usually strings, but can also be tuples or numeric types. On the other hand the items of dictionaries can be either mutable or immutable. The Python dictionary provides no guarantee that the keys are ordered.
Syntax:
dictionary = {'a': a, 'b': b, ..., 'z': z}
Structure:
Example of a dictionary:
dic = {'name': 'Dabar', 'band': 'Honey'}
Acessing elements:
print (dic['name'])
Adding elements:
dic['key_1'] = '120'
Removing one elemento from a dictionary:
del dic['key_1']
Getting the items, keys and values:
items = dic.items()
keys = dic.keys()
values = dic.values()
Examples with dictionaries:
In [2]:
dic = {'name': 'Dabar', 'name': 'Dabar New', 'band': 'Honey'}
print(dic)
print(len(dic))
NOTE: Last key will override the previous one
In [4]:
print(dic.items())
In [9]:
# Progs and their albums
progs = {'Yes': ['Close To The Edge', 'Fragile'],
'Genesis': ['Foxtrot', 'The Nursery Crime'],
'ELP': ['Brain Salad Surgery']}
# More progs
progs['King Crimson'] = ['Red', 'Discipline']
# items() returns a list of
# tuples with key and value
for singer, album in progs.items():
print(singer, ":=>", album)
In [13]:
for albums in progs.values():
print(albums)
In [14]:
for prog in progs:
print(prog, "=>", progs[prog])
In [15]:
# If there is 'ELP', removes
if 'ELP' in progs:
del progs['ELP']
print(progs)
In [4]:
multid = {'school': 'DMS',
'students_details': {
1001: {
"name": "Mayank",
"age": 41
},
1002: {
"name" : "Vishal",
"age": 42
},
1003: {
"name": "Rajeev Chaturvedi",
"age": 41
}
}
}
print(multid)
In [10]:
print(multid['students_details'][1001])
print(multid['students_details'][1002]['name'])
In [11]:
print(multid['students_details'][1004]['name'])
In [18]:
multid = {'school': 'DMS',
'students_details': {
"students":
[
"Mayank",
"Vishal",
"Rajeev"
]
}}
print(multid)
In [8]:
dupli = {
"meme" : "mjmj",
"test" : "TESt value",
"meme" : "wewe"
}
print(dupli)
for k in dupli:
print(k)
In [22]:
# Matrix in form of string
matrix = '''0 0 0 0 0 0 0 0 0 0 0 0
9 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 4 0 0
0 0 0 0 0 0 0 3 0 0 0 0
0 0 0 0 0 0 5 0 0 0 0 0
0 0 0 0 6 0 0 0 0 0 0 0'''
mat = {}
# split the matrix in lines
for row, line in enumerate(matrix.splitlines()):
# Splits the line int cols
for col, column in enumerate(line.split()):
column = int(column)
# Places the column in the result,
# if it is differente from zero
if column:
mat[row, col] = column
print (mat)
# The counting starts with zero
print ('Complete matrix size:', (row + 1) * (col + 1))
print ('Sparse matrix size:', len(mat))
NOTE: One can create dictionary using the following methods as well
In [3]:
names = dict(mayank="johri", ashwini="johri", Rahul="Johri")
print(names)
In [29]:
names = dict([("mayank","johri"), ("ashwini", "johri"), ("Rahul","Johri")])
print(names)
Lets check below two examples and see what is happening
In [16]:
d = dict()
d[10.1] = "TEST"
d[10] = "test"
d[10.5] = "really testing"
d[20] = "Testing completed"
print(d)
In [27]:
d = dict()
d[10.0] = "TEST"
d[10] = "test"
d[10.5] = "really testing"
d[20] = "Testing completed"
print(d)
NOTE: Dictionaries are implemented with a hash table and hash of 10.0 and 10 are same, thus 10.0 and 10 keys of dict are same and only one key/value pair is shown for them. Please check the url for details.
In [31]:
hash(10.0) == hash(10)
Out[31]: